<template>
  <div class="app-container">
    <!--    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">-->
    <!--      <el-form-item label="班级" prop="grades">-->
    <!--        <el-input-->
    <!--          v-model="queryParams.grades"-->
    <!--          placeholder="请输入班级"-->
    <!--          clearable-->
    <!--          @keyup.enter.native="handleQuery"-->
    <!--        />-->
    <!--      </el-form-item>-->
    <!--      <el-form-item>-->
    <!--        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>-->
    <!--        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>-->
    <!--      </el-form-item>-->
    <!--    </el-form>-->

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['edu:bank:add']"
        >新增
        </el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['edu:questionBank:edit']"
        >修改
        </el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['edu:questionBank:remove']"
        >删除
        </el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['edu:questionBank:export']"
        >导出
        </el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleText2Speech"
        >导出音频
        </el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="questionBankList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column
        label="题干"
        align="center"
        prop="title"
        show-overflow-tooltip
      />
      <el-table-column label="学科" align="center" prop="subject">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.edu_subject"
            :value="scope.row.subject"
          />
        </template>
      </el-table-column>
      <el-table-column label="题目类型" align="center" prop="questionType">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.edu_question_type"
            :value="scope.row.questionType"
          />
        </template>
      </el-table-column>
      <el-table-column label="班级" align="center" prop="grades">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.edu_grades" :value="scope.row.grades"/>
        </template>
      </el-table-column>
      <el-table-column label="难易度" align="center" prop="level">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.edu_facility_value"
            :value="scope.row.grades"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['edu:questionBank:edit']"
          >修改
          </el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['edu:questionBank:remove']"
          >删除
          </el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改题库对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="1000px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="题干" prop="title">
              <el-input
                v-model="form.title"
                type="textarea"
                placeholder="请输入内容"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="题干图片" prop="questionImage">
              <el-upload
                :file-list="upload.fileList"
                ref="upload"
                list-type="picture-card"
                :accept="questionTypeAccept"
                :limit="1"
                :headers="upload.headers"
                :action="upload.url"
                :disabled="upload.isUploading"
                :on-progress="handleFileUploadProgress"
                :on-success="handleFileSuccess"
                :on-change="handleFileChange"
              >
                <i slot="default" class="el-icon-plus"></i>
                <div slot="file" slot-scope="{ file }">
                  <img class="el-upload-list__item-thumbnail" :src="file.url" alt=""/>
                  <span class="el-upload-list__item-actions">
                    <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                      <i class="el-icon-zoom-in"></i>
                    </span>
                    <span v-if="!disabled" class="el-upload-list__item-delete"
                          @click="handlePictureRemove(file)"
                    >
                      <i class="el-icon-delete"></i>
                    </span>
                  </span>
                  <!--                  <audio-player :audio-src="file.url"/>-->
                </div>
              </el-upload>
              <el-dialog
                :visible.sync="dialogVisible"
                :modal="false"
                :lock-scroll="false"
              >
                <img width="100%" :src="dialogImageUrl" alt=""/>
              </el-dialog>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="题目类型" prop="questionType">
              <el-select
                v-model="form.questionType"
                placeholder="请选择题目类型"
                style="width: 100%" @change="clearFileList()"
              >
                <el-option
                  v-for="dict in dict.type.edu_question_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="年级" prop="grades">
              <el-select
                v-model="form.grades"
                placeholder="请选择年级"
                style="width: 100%"
              >
                <el-option
                  v-for="dict in dict.type.edu_grades"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="学科" prop="subject">
              <el-radio-group v-model="form.subject" size="mini">
                <el-radio
                  border
                  v-for="dict in dict.type.edu_subject"
                  :key="dict.value"
                  :label="dict.value"
                >{{ dict.label }}
                </el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.questionType != null && form.questionType != '2'">
          <el-col :span="12">
            <el-form-item label="选项"
                          prop="options"
                          v-if="form.questionType == '1' || form.questionType == '4'"
            >
              <el-input v-model="form.choiceOptions.A" placeholder="请输入内容">
                <i slot="prefix">A</i>
              </el-input>
              <el-input v-model="form.choiceOptions.B" placeholder="请输入内容">
                <i slot="prefix">B</i>
              </el-input>
              <el-input v-model="form.choiceOptions.C" placeholder="请输入内容">
                <i slot="prefix">C</i>
              </el-input>
              <el-input v-model="form.choiceOptions.D" placeholder="请输入内容">
                <i slot="prefix">D</i>
              </el-input>
            </el-form-item>
            <el-form-item
              label="选项"
              prop="options"
              v-if="form.questionType == '3'"
            >
              <el-input
                v-model="form.trueFalseOptions.A"
                readonly
                placeholder="请输入内容"
              >
                <i slot="prefix">A</i>
              </el-input>
              <el-input
                v-model="form.trueFalseOptions.B"
                readonly
                placeholder="请输入内容"
              >
                <i slot="prefix">B</i>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="答案" prop="answer">
              <el-input v-model="form.answer" placeholder="请输入答案"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.questionType == '2'">
          <el-col :span="24">
            <el-form-item label="答案" prop="answer">
              <el-input
                v-model="form.answer"
                type="textarea"
                placeholder="请输入答案"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="难易度" prop="level">
              <el-radio-group v-model="form.level" size="mini">
                <el-radio
                  border
                  v-for="dict in dict.type.edu_facility_value"
                  :key="dict.value"
                  :label="dict.value"
                >{{ dict.label }}
                </el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="得分" prop="points">
              <el-input v-model="form.points" placeholder="请输入得分"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="答案分析" prop="questionAnalysis">
              <el-input
                v-model="form.questionAnalysis"
                type="textarea"
                placeholder="请输入内容"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="答案附件" prop="analysisAttachment">
              <el-upload
                class="upload-demo"
                ref="upload"
                :limit="1"
                :headers="upload.headers"
                :action="upload.url"
                :file-list="upload.analysisFileList"
                :disabled="upload.isAnalysisUploading"
                :on-progress="handleAnalysisFileUploadProgress"
                :on-success="handleAnalysisFileSuccess"
                :on-change="handleAnalysisFileChange"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="音频导出" :visible.sync="speechOpen" width="1000px" append-to-body>
      <el-form ref="speechForm"  :rules="speechRules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="语音文本" prop="speechText">
              <el-input v-model="speechText" type="textarea" placeholder="请输入内容"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="exportSpeech">确 定</el-button>
        <el-button @click="cancelSpeech">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listQuestionBank,
  getQuestionBank,
  delQuestionBank,
  addQuestionBank,
  updateQuestionBank
} from '@/api/edu/questionBank'
import { getToken } from '@/utils/auth'
import AudioPlayer from '@/views/edu/questionBank/AudioPlayer'

export default {
  name: 'QuestionBank',
  dicts: [
    'edu_question_type',
    'edu_grades',
    'edu_facility_value',
    'edu_subject'
  ],
  components: { AudioPlayer },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 题库表格数据
      questionBankList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      speechOpen: false,
      speechText:null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        questionType: null,
        options: null,
        answer: null,
        knowledgePoints: null,
        grades: null,
        level: null,
        questionAnalysis: null,
        tenantId: null,
        tenantName: null
      },
      // 表单参数
      form: {},
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      upload: {
        // 是否禁用上传
        isUploading: false,
        isAnalysisUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/edu/question/bank/uploadFile',
        fileList: [],
        analysisFileList: []
      },
      // 表单校验
      rules: {
        title: [{ required: true, message: '题干不能为空', trigger: 'blur' }],
        questionType: [
          { required: true, message: '题目类型不能为空', trigger: 'blur' }
        ],
        grades: [{ required: true, message: '年级不能为空', trigger: 'blur' }],
        subject: [{ required: true, message: '学科不能为空', trigger: 'blur' }],
        level: [{ required: true, message: '难易度不能为空', trigger: 'blur' }]
      },
      speechRules:{
        speechText: [{ required: true, message: '语音文本不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
  },
  computed: {
    questionTypeAccept() {
      return !this.form.questionType || this.form.questionType !== '4' ? '.png,.jpg' : '.wav,pcm'
    }
  },
  methods: {
    /** 查询题库列表 */
    getList() {
      this.loading = true
      listQuestionBank(this.queryParams).then((response) => {
        this.questionBankList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 取消按钮
    cancelSpeech() {
      this.speechOpen = false
      this.speechText = "";
    },
    // 表单重置
    reset() {
      this.upload.fileList = []
      this.upload.analysisFileList = []
      this.form = {
        id: null,
        title: null,
        questionImage: null,
        questionType: null,
        options: null,
        answer: null,
        points: null,
        knowledgePoints: null,
        grades: null,
        level: null,
        subject: null,
        questionAnalysis: null,
        analysisAttachment: null,
        tenantId: null,
        tenantName: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        choiceOptions: {
          A: null,
          B: null,
          C: null,
          D: null
        },
        trueFalseOptions: {
          A: '正确',
          B: '错误'
        }
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加题库'
    },
    handleText2Speech() {
      this.speechText = ''
      this.speechOpen = true
    },
    clearFileList() {
      this.upload.fileList = []
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getQuestionBank(id).then((response) => {
        this.form = response.data
        if (!this.form.choiceOptions) {
          this.form.choiceOptions = {
            A: null,
            B: null,
            C: null,
            D: null
          }
        }
        if (!this.form.trueFalseOptions) {
          this.form.trueFalseOptions = {
            A: '正确',
            B: '错误'
          }
        }
        if (this.form.questionImage) {
          this.dialogImageUrl =
            process.env.VUE_APP_BASE_API +
            this.form.questionImage +
            '?t=' +
            new Date().getTime()
          this.upload.fileList = [
            { name: '当前题目图片', url: this.dialogImageUrl }
          ]
        }
        if (this.form.analysisAttachment) {
          let fileName = this.form.analysisAttachment.split('/').pop()
          this.upload.analysisFileList = [
            {
              name: fileName,
              url: process.env.VUE_APP_BASE_API + this.form.analysisAttachment + '?t=' + new Date().getTime()
            }
          ]
        }
        this.open = true
        this.title = '修改题库'
      })
    },
    handlePictureRemove(file) {
      // 1. 先移除本地列表
      this.$refs.upload.handleRemove(file)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleDownload(file) {
      console.log(file)
    },
    // 文件上传 TODO: 文件上传发生变化就会触发
    handleFileChange(file, fileList) {
      console.log(file, fileList)
      console.log(1231)
    },
    // 文件上传 TODO: 文件上传发生变化就会触发
    handleAnalysisFileChange(file, fileList) {
      console.log(file, fileList)
      console.log(1231)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传中处理
    handleAnalysisFileUploadProgress(event, file, fileList) {
      this.upload.isAnalysisUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.isUploading = false
      // this.$refs.upload.clearFiles()
      // console.log(JSON.stringify(response))
      this.form.questionImage = response.msg + '?t=' + new Date().getTime()
    },
    // 文件上传成功处理
    handleAnalysisFileSuccess(response, file, fileList) {
      this.upload.isAnalysisUploading = false
      // this.$refs.upload.clearFiles()
      // console.log(JSON.stringify(response))
      this.form.analysisAttachment = response.msg + '?t=' + new Date().getTime()
      console.log(this.form.analysisAttachment)
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateQuestionBank(this.form).then((response) => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addQuestionBank(this.form).then((response) => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal
        .confirm('是否确认删除题库编号为"' + ids + '"的数据项？')
        .then(function() {
          return delQuestionBank(ids)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'edu/question/bank/export',
        {
          ...this.queryParams
        },
        `bank_${new Date().getTime()}.xlsx`
      )
    },
    exportSpeech(){
      this.download(
        '/student/lib/text2Speech',
        {
          text:this.speechText
        },
        `bank_${new Date().getTime()}.wav`
      )
    }
  }
}
</script>
